var express = require('express');
var router = express.Router();
var crypto = require('crypto'),User = require('../models/user');
var Post = require('../models/post');
var Comment = require('../models/comment')
var prefresher = require('../models/prefresher');
var fresher = require('../models/fresher');
/* GET home page. */
/*
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

module.exports = router;
*/
module.exports = function (app) {
    //index
    app.get('/', function(req, res, next) {
        res.render('index', {
            title: '首页',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    /* 为robocup招新开辟的通道*/
    //prefresher
    app.get('/prefresher', function(req, res, next){
        res.render('prefresher',{
            title: 'robocup实验室预招新',
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    app.post('/prefresher', function(req, res, next) {
        var name = req.body.name;

        var newprefresher = new prefresher({
            name: req.body.name,
            stuNum: req.body.stuNum,
            stuQnumber: req.body.stuQnumber,
            stuPhone: req.body.stuPhone,
            stuMajor: req.body.stuMajor,
            stuTeam: req.body.stuTeam
        });

        //检查用户名是否已经存在
        prefresher.get(newprefresher.stuNum,function (err, stu) {
            if(err) {
                req.flash('error',err);
                return res.redirect('/prefresher');
            }
            if(stu) {
                req.flash('error','不能重复报名！');
                return res.redirect('/prefresher');//返回注册页
            }
            //如果不存在则增加新用户
            newprefresher.save(function (err,stu) {
                if(err){
                    req.flash('error', err);
                    return res.redirect('/prefresher'); //注册失败返回注册页
                }
                req.flash('success','报名成功！');
                res.redirect('/prefresher'); //注册成功返回主页
            });
        });
    });
    //prefresherlook
    app.get('/prefresherlook', function(req, res, next) {
        prefresher.getAll(null,function (err, stus) {
            if(err){
                stus = [];
            }
            res.render('prefresherlook', {
                stus: stus,
                success:req.flash('success').toString(),
                error: req.flash('error').toString()
            });
        });
    });
    //fresher
    app.get('/fresher', function(req, res, next){
        res.render('fresher',{
            title: 'robocup实验室预招新',
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    app.post('/fresher', function(req, res, next) {
        var name = req.body.name;

        var newfresher = new fresher({
            name: req.body.name,
            stuNum: req.body.stuNum,
            stuQnumber: req.body.stuQnumber,
            stuPhone: req.body.stuPhone,
            stuMajor: req.body.stuMajor,
            stuTeam: req.body.stuTeam
        });

        //检查用户名是否已经存在
        fresher.get(newfresher.stuNum,function (err, stu) {
            if(err) {
                req.flash('error',err);
                return res.redirect('/fresher');
            }
            if(stu) {
                req.flash('error','不能重复报名！');
                return res.redirect('/fresher');//返回注册页
            }
            //如果不存在则增加新用户
            newfresher.save(function (err,stu) {
                if(err){
                    req.flash('error', err);
                    return res.redirect('/fresher'); //注册失败返回注册页
                }
                req.flash('success','报名成功！');
                res.redirect('/fresher'); //注册成功返回主页
            });
        });
    });
    //fresher
    app.get('/fresherlook', function(req, res, next) {
        fresher.getAll(null,function (err, stus) {
            if(err){
                stus = [];
            }
            res.render('fresherlook', {
                stus: stus,
                success:req.flash('success').toString(),
                error: req.flash('error').toString()
            });
        });
    });
    //reg
    app.get('/reg',checkNotLogin);
    app.get('/reg', function(req, res, next) {
        res.render('reg', {
            title: '注册',
            user: req.session.user,
            success:req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    app.post('/reg',checkNotLogin);
    app.post('/reg', function(req, res, next) {
        var name = req.body.name,
            password = req.body.password,
            password_re = req.body['password-repeat'];
        //检验用户两次输入是否一致
        if(password_re != password){
            req.flash('error','两次输入的密码不一致');
            return res.redirect('/reg'); //返回注册页面
        }
        //生成密码的 md5 值
        var md5 = crypto.createHash('md5'),
            password = md5.update(req.body.password).digest('hex');
        var newUser = new User({
            name: req.body.name,
            password: password,
            email: req.body.email
        });
        //检查用户名是否已经存在
        User.get(newUser.name,function (err, user) {
            if(err) {
                req.flash('error',err);
                return res.redirect('/blog');
            }
            if(user) {
                req.flash('error','用户已经存在！');
                return res.redirect('/reg');//返回注册页
            }
            //如果不存在则增加新用户
            newUser.save(function (err,user) {
                if(err){
                    req.flash('error', err);
                    return res.redirect('/reg'); //注册失败返回注册页
                }
                req.session.user = user; //用户信息存入session
                req.flash('success','注册成功！');
                res.redirect('/blog'); //注册成功返回主页
            });
        });
    });
    //login
    app.get('/reg',checkNotLogin);
    app.get('/login', function(req, res, next) {
        res.render('login', {
            title: '登录',
            user: req.session.user,
            success:req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    app.post('/reg',checkNotLogin);
    app.post('/login', function(req, res, next) {
        //生成密码的 md5 值
        var md5 = crypto.createHash('md5'),
            password = md5.update(req.body.password).digest('hex');
        //检查用户是否存在
        User.get(req.body.name, function (err, user) {
            if(!user) {
                req.flash('error', '用户不存在');
                return res.redirect('/login'); //用户不存在则跳转到登录界面
            }
            //检查密码是否一致
            if(user.password != password) {
                req.flash('error', '密码错误！');
                return res.redirect('/login');//密码错误则跳转到登录界面
            }
            //用户名和密码都匹配后,将用用户信息存入session
            req.session.user = user;
            req.flash('success','登录成功！');
            res.redirect('/');//登录成功后跳转到主页
        });
    });
    //logout
    app.get('/logout',checkLogin);
    app.get('/logout', function(req, res, next) {
        req.session.user = null;
        req.flash('success','登出成功！');
        res.redirect('/');
    });
    //blog
    app.get('/blog', function(req, res, next) {
        Post.getAll(null,function (err, posts) {
            if(err){
                posts = [];
            }
            res.render('blog', {
                user: req.session.user,
                posts: posts,
                success:req.flash('success').toString(),
                error: req.flash('error').toString()
            });
        });
    });
    //blog-post
    app.get('/post',checkLogin);
    app.get('/post',function(req, res, next) {
        res.render('post', {
            title: '发表',
            user: req.session.user,
            success:req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    app.post('/post',checkLogin);
    app.post('/post',function(req, res, next) {
        var currentUser = req.session.user,
            post = new Post(currentUser.name, req.body.title, req.body.post);
        post.save(function (err) {
            if(err){
                req.flash('error',err);
                return res.redirect('/post');//发布失败留在当前界面
            }
            req.flash('success','发布成功');
            return res.redirect('/blog');//发布成功跳转到blog
        });
    });
    //user-all-article
    app.get('/u/:name',function (req, res) {
        //检查用户是否存在
        User.get(req.params.name,function (err, user) {
            if(!user){
                req.flash('error','用户不存在');
                return res.redirect('/');
            }
            //查询并返回该用户的所有文章
            Post.getAll(user.name,function (err,posts) {
               if(err){
                   req.flash('error',err);
                   return res.redirect('/');
               }
               res.render('user',{
                   title: user.name,
                   posts: posts,
                   user: req.session.user,
                   success: req.flash('success').toString(),
                   error: req.flash('error').toString()
               });
            });
        });
    });
    //single article
    app.get('/id/:id',function (req, res) {
        Post.getOne(req.params.id,function (err, post) {
            if(err){
                req.flash('error',err);
                return res.redirect('/');
            }
            res.render('article',{
                title: req.params.title,
                post: post,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            });
        });
    });
    //edit
    app.get('/edit/:id',checkLogin);
    app.get('/edit/:id',function (req,res) {
        Post.edit(req.params.id, function (err, post) {
            if(err){
                req.flash('error',err);
                /*return res.redirect('back');*/
                return res.redirect('/');
            }
            res.render('edit',{
                title: '编辑',
                post: post,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            });
        });
    });
    app.post('/edit/:id',checkLogin);
    app.post('/edit/:id',function (req,res) {
        Post.update(req.params.id, req.body.post, function (err) {
            var url = encodeURI('/id/'+req.params.id);
            if(err){
                req.flash('error',err);
                return res.redirect(url);//出错，返回文章页
            }
            req.flash('success','修改成功！');
            res.redirect(url);//成功，返回文章页
        });
    });
    //delete
    app.get('/remove/:id',checkLogin);
    app.get('/remove/:id',function (req,res) {
        Post.remove(req.params.id,function(err){
            if(err){
                req.flash('error',err);
                return res.redirect('back');
            }
            req.flash('success','删除成功！');
            res.redirect('/blog');
        });
    });
    //comment
    app.post('/id/:id',function (req,res) {
        var date = new Date(),
            time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes());
        var comment = {
            name: req.body.name,
            email: req.body.email,
            time: time,
            content: req.body.content
        };
        var newComment = new Comment(req.params.id, comment);
        newComment.save(function (err) {
            if(err){
                req.flash('error',err);
                return res.redirect('back');
            }
            req.flash('success','留言成功！');
            res.redirect('back');
        });
    });
};

//页面权限控制
function checkLogin(req,res,next) {
    if(!req.session.user){
        req.flash('error','未登录！');
        res.redirect('login');
    }
    next();
}

function checkNotLogin(req,res,next) {
    if(req.session.user){
        req.flash('error','已登录');
        res.redirect('back');//返回之前的页面
    }
    next();
}